<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <el-card class="box-card">
          <template v-slot:header>
            <div class="clearfix">
              <span>个人信息</span>
            </div>
          </template>
          <div>
            <div class="text-center">
              <el-image style="width: 160px; height: 160px; border-radius: 160px"
                        :src="avatar"
              />
            </div>

            <div class="divst-group divst-group-striped">

              <el-divider/>

              <div class="divst-group-item">
                <el-icon>
                  <User/>
                </el-icon>
                <div>用户姓名</div>
                <div class="pull-right">{{ user.name }}</div>
              </div>

              <el-divider/>

              <div class="divst-group-item">
                <el-icon v-if="user.sexText === '男'">
                  <Female/>
                </el-icon>
                <el-icon v-else-if="user.sexText === '女'">
                  <Male/>
                </el-icon>
                <div>用户性别</div>
                <div class="pull-right">{{ user.sexText }}</div>
              </div>

              <el-divider/>

              <div class="divst-group-item">
                <el-icon>
                  <Iphone/>
                </el-icon>
                <div>手机号码</div>
                <div class="pull-right">{{ user.phone }}</div>
              </div>

              <el-divider/>

              <div class="divst-group-item">
                <el-icon>
                  <Message/>
                </el-icon>
                <div>用户邮箱</div>
                <div class="pull-right">{{ user.email }}</div>
              </div>

              <el-divider/>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18" :xs="24">
        <el-card>
          <template v-slot:header>
            <div class="clearfix">
              <span>基本资料</span>
            </div>
          </template>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本资料" name="userinfo">
              <el-form
                  ref="baseInfoRef"
                  label-position="right"
                  label-width="160px"
                  style="margin-right: 20px"
                  status-icon
                  :model="baseInfoForm"
                  :rules="baseInfoRules"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户姓名：" prop="name">
                      <el-input
                          v-model="baseInfoForm.name"
                          placeholder="请输入用户姓名"
                          clearable
                          show-word-limit
                          maxlength="50"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="用户性别：" prop="sex">
                      <el-radio-group v-model="baseInfoForm.sex">
                        <el-radio value="1">男</el-radio>
                        <el-radio value="2">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户学号：" prop="studentNumber">
                      <el-input
                          v-model="baseInfoForm.studentNumber"
                          placeholder="请输入用户学号"
                          clearable
                          show-word-limit
                          maxlength="20"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="用户年龄：" prop="age">
                      <el-input-number v-model="baseInfoForm.age"
                                       style="width: 62%"
                                       controls-position="right"
                                       placeholder="请输入用户年龄"
                                       show-word-limit
                                       :max="999"
                      >
                        <template #decrease-icon>
                          <el-icon>
                            <Minus/>
                          </el-icon>
                        </template>
                        <template #increase-icon>
                          <el-icon>
                            <Plus/>
                          </el-icon>
                        </template>
                      </el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户电话：" prop="phone">
                      <el-input
                          v-model="baseInfoForm.phone"
                          placeholder="请输入用户电话"
                          clearable
                          show-word-limit
                          maxlength="20"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="用户邮箱：" prop="email">
                      <el-input
                          v-model="baseInfoForm.email"
                          placeholder="请输入用户邮箱"
                          clearable
                          show-word-limit
                          maxlength="100"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户学院：" prop="college">
                      <el-input
                          v-model="baseInfoForm.college"
                          placeholder="请输入用户学院"
                          clearable
                          show-word-limit
                          maxlength="100"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="用户专业：" prop="major">
                      <el-input
                          v-model="baseInfoForm.major"
                          placeholder="请输入用户专业"
                          clearable
                          show-word-limit
                          maxlength="100"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户班级：" prop="grade">
                      <el-input
                          v-model="baseInfoForm.grade"
                          placeholder="请输入用户班级"
                          clearable
                          show-word-limit
                          maxlength="100"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="身份证号：" prop="idCard">
                      <el-input
                          v-model="baseInfoForm.idCard"
                          placeholder="请输入身份证号"
                          clearable
                          show-word-limit
                          maxlength="20"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="出生日期：" prop="birthday">
                      <el-date-picker
                          v-model="baseInfoForm.birthday"
                          style="width: 100%;"
                          type="datetime"
                          placeholder="请选择出生日期"
                          format="YYYY-MM-DD HH:mm:ss"
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="入学时间：" prop="enterTime">
                      <el-date-picker
                          v-model="baseInfoForm.enterTime"
                          style="width: 100%;"
                          type="datetime"
                          placeholder="请选择入学时间"
                          format="YYYY-MM-DD HH:mm:ss"
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="用户地址：" prop="address">
                      <el-input
                          v-model="baseInfoForm.address"
                          maxlength="255"
                          placeholder="请选择用户地址"
                          show-word-limit
                          type="textarea"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>


                <el-row :gutter="20">
                  <el-col :span="24">
                    <div style="display: flex; justify-content: center; align-items: center;">
                      <el-button type="primary" plain @click="saveButton(baseInfoRef)">保存</el-button>
                      <el-button type="warning" plain @click="resetButton">重置</el-button>
                    </div>
                  </el-col>
                </el-row>

                <el-divider/>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="resetPwd">
              <el-form
                  ref="passwordRef"
                  label-position="right"
                  label-width="160px"
                  style="margin-right: 20px"
                  status-icon
                  :model="passwordForm"
                  :rules="passwordRules"
              >
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="旧密码：" prop="oldPassword">
                      <el-input
                          v-model="passwordForm.oldPassword"
                          placeholder="请输入旧密码"
                          clearable
                          type="password"
                          show-password
                          show-word-limit
                          maxlength="100"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="新密码：" prop="newPassword">
                      <el-input
                          v-model="passwordForm.newPassword"
                          placeholder="请输入新密码"
                          clearable
                          type="password"
                          show-password
                          show-word-limit
                          maxlength="100"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="确认密码：" prop="confirmPassword">
                      <el-input
                          v-model="passwordForm.confirmPassword"
                          placeholder="请输入确认密码"
                          clearable
                          type="password"
                          show-password
                          show-word-limit
                          maxlength="100"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="24">
                    <div style="display: flex; justify-content: center; align-items: center;">
                      <el-button type="primary" plain @click="updatePasswordButton(passwordRef)">保存</el-button>
                      <el-button type="warning" plain @click="resetPassword">重置</el-button>
                    </div>
                  </el-col>
                </el-row>

                <el-divider/>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted} from "vue";
import avatar from "@/assets/images/avatar/avatar.jpg";
import {Female, Iphone, Male, Message, Minus, Plus, User} from "@element-plus/icons-vue";
import {FormInstance, FormRules} from "element-plus";
import useUserStore from "@/store/modules/user/user.ts";
import {getBaseUserInfo, getToken} from "@/utils/token.ts";
import { updateUserBaseInfo} from "@/api/user/user.ts";
import {ApiResponse} from "@/utils/request.ts";
import {updatePassword} from "@/api/login/login.ts";

const userStore = useUserStore();
const activeTab = ref("userinfo");
const token = getToken() || '';
const user = ref<{
  name: string,
  sexText: string,
  age: number,
  phone: string,
  email: string,
  birthday: string,
  address: string
}>({
  name: '',
  sexText: '',
  age: 0,
  phone: '',
  email: '',
  birthday: '',
  address: ''
});

/**
 * 表单数据定义
 */
const baseInfoRef = ref<FormInstance>();

/**
 * 表单校验定义
 */
const baseInfoForm = ref({
  name: '',
  sex: '1',
  sexText: '',
  studentNumber: '',
  age: 0,
  college: '',
  major: '',
  grade: '',
  idCard: '',
  enterTime: '',
  email: '',
  phone: '',
  birthday: '',
  address: '',
  token: ''
})

/**
 * 表单数据定义
 */
const passwordRef = ref<FormInstance>();

/**
 * 密码表单数据定义
 */
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  token: ''
})

/**
 * 保存按钮
 */
const saveButton = async (ruleFormRef: FormInstance | undefined) => {
  if (!ruleFormRef) {
    return;
  }
  await ruleFormRef.validate(async (valid) => {
    if (!valid) {
      ElNotification({
        title: 'Warning',
        type: 'warning',
        message: '请检查表单必填选项'
      })
      return
    }
    baseInfoForm.value.token = token;
    const result: ApiResponse<any> = await updateUserBaseInfo(baseInfoForm.value)
    //添加或者更新成功
    if (result.code !== 1000_0000) {
      ElMessage({type: 'error', message: result.msg});
      return
    }
    ElMessage({type: 'success', message: '更新成功'});
    await userStore.getUserInfo();
    let userInfo = getBaseUserInfo();
    userInfo.age = Number(userInfo.age)
    user.value = JSON.parse(JSON.stringify(userInfo));
    baseInfoForm.value = JSON.parse(JSON.stringify(userInfo));
  })
}

/**
 * 保存按钮
 */
const updatePasswordButton = async (ruleFormRef: FormInstance | undefined) => {
  if (!ruleFormRef) {
    return;
  }
  await ruleFormRef.validate(async (valid) => {
    if (!valid) {
      ElNotification({
        title: 'Warning',
        type: 'warning',
        message: '请检查表单必填选项'
      })
      return
    }
    passwordForm.value.token = token;
    const result: ApiResponse<any> = await updatePassword(passwordForm.value)
    //添加或者更新成功
    if (result.code !== 1000_0000) {
      ElMessage({type: 'error', message: result.msg});
      return
    }
    ElMessage({type: 'success', message: '更新成功'});
    resetPassword();
  })
}

/**
 * 重置按钮
 */
const resetButton = () => {
  baseInfoForm.value = {
    name: '',
    sex: '1',
    sexText: '',
    studentNumber: '',
    age: 0,
    college: '',
    major: '',
    grade: '',
    idCard: '',
    enterTime: '',
    email: '',
    phone: '',
    birthday: '',
    address: '',
    token: ''
  }
}

/**
 * 重置密码按钮
 */
const resetPassword = () => {
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
    token: ''
  }
}

/**
 * 校验规则定义
 */
const baseInfoRules = ref<FormRules>({
  name: [
    {
      required: true,
      message: '请输入用户姓名',
      trigger: 'blur'
    }
  ],
  sex: [
    {
      required: true,
      message: '请选择用户性别',
      trigger: 'change',
    },
  ],
  studentNumber: [
    {
      required: true,
      message: '请输入用户学号',
      trigger: 'blur'
    }
  ],
  age: [
    {
      required: true,
      message: '请输入用户年龄',
      trigger: 'blur'
    }
  ],
  phone: [
    {
      required: true,
      message: '请输入用户电话',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入用户邮箱',
      trigger: 'blur'
    }
  ],
  idCard: [
    {
      required: true,
      message: '请输入正确的身份证号',
      trigger: 'blur'
    }
  ],
  birthday: [
    {
      required: true,
      message: '请选择出生日期',
      trigger: 'change'
    }
  ],
  address: [
    {
      required: true,
      message: '请输入用户地址',
      trigger: 'blur'
    }
  ]
});

/**
 * 校验规则定义
 */
const passwordRules = ref<FormRules>({
  oldPassword: [
    {
      required: true,
      message: '请输入旧密码',
      trigger: 'blur'
    }
  ],
  newPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {required: true, message: '请输入确认密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback('两次密码输入不一致')
        }
        callback()
      }
    }]
});


// 获取用户信息
onMounted(() => {
  userStore.getUserInfo();
  let userInfo = getBaseUserInfo();
  userInfo.age = Number(userInfo.age)
  user.value = JSON.parse(JSON.stringify(userInfo));
  baseInfoForm.value = JSON.parse(JSON.stringify(userInfo));
})

</script>

<style scoped lang="scss">
.text-center {
  display: flex;
  justify-content: center;
  align-content: center;
}

.divst-group-item {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .pull-right {
    margin-left: auto;
  }
}
</style>
